package com.itheima.controller;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.SMSUtils;
import com.itheima.common.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/validatecode")
public class ValidatecodeController {

    @Autowired
    private SMSUtils smsUtils;


    @Autowired
    private RedisTemplate redisTemplate;

    //发送短信验证码
    @RequestMapping("/send4Order")
    public Result send4Login(@RequestParam String telephone) {
        log.info("发送短信验证码:{}", telephone);
        //生成随机数验证码
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        log.info("验证码:{}", code);

        //验证码保存到redis，保存5分钟，超时自动删除
        redisTemplate.opsForValue().set(telephone, code.toString(), 100, TimeUnit.MINUTES);

        smsUtils.sendMessage(SMSUtils.ACCESSKEYID, telephone, code.toString());


        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    //手机号快速登录发送验证码
    @GetMapping ("/send4Login")
    public Result send6Login(@RequestParam String telephone) {
        log.info("发送短信验证码:{}", telephone);
        //生成随机数验证码
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        log.info("验证码:{}", code);

        //验证码保存到redis，保存5分钟，超时自动删除
        redisTemplate.opsForValue().set(telephone, code.toString(), 100, TimeUnit.MINUTES);

        smsUtils.sendMessage(SMSUtils.ACCESSKEYSECRET , telephone, code.toString());

        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
